package org.hfy.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.hfy.entity.Employee;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 * 
 * @author hfy
 * @version 1.0
 */
@Component
public class JwtUtils {

    // 过期时间24小时
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;
    
    // 密钥
    @Value("${jwt.secret:pcberp-system-secret-key}")
    private String secret;
    
    /**
     * 生成token
     * 
     * @param employee 员工信息
     * @return token
     */
    public String generateToken(Employee employee) {
        // 设置过期时间
        Date expirationDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        
        // 设置header
        Map<String, Object> header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");
        
        // 设置payload
        Map<String, Object> payload = new HashMap<>();
        payload.put("id", employee.getId());
        payload.put("employeeCode", employee.getEmployeeCode());
        payload.put("employeeName", employee.getEmployeeName());
        payload.put("role", employee.getRole());
        payload.put("exp", expirationDate.getTime());
        payload.put("iat", System.currentTimeMillis());
        
        // 生成token
        String headerBase64 = Base64.getEncoder().encodeToString(JSONUtil.toJsonStr(header).getBytes(StandardCharsets.UTF_8));
        String payloadBase64 = Base64.getEncoder().encodeToString(JSONUtil.toJsonStr(payload).getBytes(StandardCharsets.UTF_8));
        
        // 生成签名
        String signature = SecureUtil.hmacSha256(secret)
                .digestHex(headerBase64 + "." + payloadBase64);
        
        return headerBase64 + "." + payloadBase64 + "." + signature;
    }
    
    /**
     * 验证token
     * 
     * @param token token
     * @return 是否有效
     */
    public boolean validateToken(String token) {
        try {
            String[] parts = token.split("\\.");
            if (parts.length != 3) {
                return false;
            }
            
            // 验证签名
            String headerBase64 = parts[0];
            String payloadBase64 = parts[1];
            String signature = parts[2];
            
            String newSignature = SecureUtil.hmacSha256(secret)
                    .digestHex(headerBase64 + "." + payloadBase64);
            
            if (!newSignature.equals(signature)) {
                return false;
            }
            
            // 解析payload
            String payloadJson = new String(Base64.getDecoder().decode(payloadBase64), StandardCharsets.UTF_8);
            JSONObject payload = JSONUtil.parseObj(payloadJson);
            
            // 验证过期时间
            long expTime = payload.getLong("exp");
            return System.currentTimeMillis() <= expTime;
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 从token中获取员工ID
     * 
     * @param token token
     * @return 员工ID
     */
    public Long getEmployeeIdFromToken(String token) {
        try {
            String[] parts = token.split("\\.");
            String payloadBase64 = parts[1];
            
            String payloadJson = new String(Base64.getDecoder().decode(payloadBase64), StandardCharsets.UTF_8);
            JSONObject payload = JSONUtil.parseObj(payloadJson);
            
            return payload.getLong("id");
        } catch (Exception e) {
            return null;
        }
    }
} 